// 树形数据

// 一般的树形数据都有这些选项

let tree = [
    {
        id: 1,
        title: '主页',
        children: [
            {
                id: 3,
                pid: 1,
                title: '欢迎',
            },
            {
                id: 4,
                pid: 1,
                title: "学员管理",
                children: [
                    {
                        id: 5,
                        pid: 4,
                        title: '测试'
                    }
                ]
            }
        ]
    },
    {
        id: 2,
        title: '用户中心'
    }
]

//树形数据扁平化

function repeatTree(data) {
    let repeatArr = [];
    function recursion(data) {
        data.forEach(item => {
            if (item.children) {
                recursion(item.children)
            }
            repeatArr.push({
                id: item.id,
                title: item.title,
                pid: item.pid ?? ""
            })
        })
    }
    recursion(data)
    return repeatArr;
}

let res = repeatTree(tree)

console.log(res)

//扁平数据树形化

// 0: {id: 3, title: '欢迎', pid: 1}
// 1: {id: 5, title: '测试', pid: 4}
// 2: {id: 4, title: '学员管理', pid: 1}
// 3: {id: 1, title: '主页', pid: ''}
// 4: {id: 2, title: '用户中心', pid: ''}

function convertTree(repeatArr) {
    let tree = [];
    repeatArr.forEach(item => {
        //爸爸在哪里 查找自己的父节点
        let parent = repeatArr.find(v => item.pid === v.id)
        // console.log(parent)
        if (parent) {
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(item)
        } else {
            tree.push(item)
        }
    })
    return tree
}

let res2 = convertTree(res)

console.log(res2)